package com.revzone.demo001.PermissionModule.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.revzone.demo001.LogModule.aspect.OperationLog;
import com.revzone.demo001.PermissionModule.mapper.RoleMapper;
import com.revzone.demo001.PermissionModule.mapper.UserAndRoleMapper;
import com.revzone.demo001.PermissionModule.service.RoleService;
import com.revzone.demo001.entity.ExciptionEntity.AppException;
import com.revzone.demo001.entity.OtherEntity.BaseEntity;
import com.revzone.demo001.entity.OtherEntity.PageResult;
import com.revzone.demo001.entity.OtherEntity.R;
import com.revzone.demo001.entity.PermissionEntity.Role;
import com.revzone.demo001.entity.PermissionEntity.RoleDTO;
import com.revzone.demo001.entity.PermissionEntity.UserAndRole;
import com.revzone.demo001.enums.PermissionEnums.EnumOperationLog;
import com.revzone.demo001.enums.PermissionEnums.EnumTypeValue;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
 * <p>
 *  角色实现类
 * </p>
 *
 * @author lsa
 * @since 2023-03-27
 */
@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements RoleService {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    RoleMapper roleMapper;
    @Autowired
    UserAndRoleMapper userAndRoleMapper;

    @Override
    @OperationLog(value = EnumTypeValue.USER_PERMISSIONS, description = EnumOperationLog.ROLE_PAGINATION_SEARCH)
    public R getRoleListPage(RoleDTO roleDTO) {
        HashMap<String, Object> map = new HashMap<>();

        IPage<Role> reFindByPage;
        try {
            Role role = new Role();
            Page<Role> page = new Page<>(roleDTO.getCurrentPage(),roleDTO.getPageSize());
            BeanUtils.copyProperties(roleDTO, role);
            QueryWrapper<Role> wrapper = BaseEntity.getQueryWrapper(role);
            if(role.getStatus()!= null)wrapper.eq("status",role.getStatus());
            // 执行分页查询
            reFindByPage = roleMapper.selectPage(page,wrapper);
        } catch (Exception e) {
            // 抛出自定义异常
            logger.error("角色分页查询失败！",e);
            throw new AppException("角色分页查询失败！");
        }
        // 将查询结果封装到 PageResult 类型的对象中
        PageResult<Role> result = new PageResult<Role>(reFindByPage);
        // 将结果存入 HashMap 并返回包含 HashMap 的 R 对象
        map.put("data",result);
        return R.ok(map);
    }

    @Override
    @OperationLog(value = EnumTypeValue.USER_PERMISSIONS, description = EnumOperationLog.ROLE_QUERY)
    public R getRoleList(RoleDTO roleDTO) {
        HashMap<String, Object> map = new HashMap<>();
        Role role = new Role();
        BeanUtils.copyProperties(roleDTO, role);
        QueryWrapper<Role> wrapper = BaseEntity.getQueryWrapper(role);
        if(role.getStatus()!= null)wrapper.eq("status",role.getStatus());
        List<Role> reFindBy = roleMapper.selectList(wrapper);
        map.put("data",reFindBy);
        return R.ok(map);
    }

    @Override
    @OperationLog(value = EnumTypeValue.USER_PERMISSIONS, description = EnumOperationLog.ROLE_ADDITION)
    public R setUserList(RoleDTO roleDTO) {
        int insert;
        QueryWrapper<Role> wrapper = new QueryWrapper<>();
        wrapper.eq("role_name", roleDTO.getRoleName());
        Role old_role = roleMapper.selectOne(wrapper);

        if (old_role != null) {
            throw new AppException("重复角色名！");
        }
        try {
            Role role = new Role();
            BeanUtils.copyProperties(roleDTO, role);
            role.setCreateDate(new Date());
            role.setUpdateDate(new Date());
            insert = roleMapper.insert(role);
        } catch (Exception e) {
            throw new AppException("新增角色失败！");
        }
        if (insert != 0) {
            return R.ok("success");
        } else return R.error("Failure");
    }

    @Override
    @OperationLog(value = EnumTypeValue.USER_PERMISSIONS, description = EnumOperationLog.ROLE_MODIFICATION)
    public R updateUserList(RoleDTO roleDTO) {
        int update;
        QueryWrapper<Role> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("role_name",roleDTO.getRoleName());
        Role old_role = roleMapper.selectById(roleDTO.getId());
        if (!old_role.getRoleName().equals(roleDTO.getRoleName())
                && roleMapper.selectOne(queryWrapper) != null) {
            throw new AppException("重复用户名！");
        }

        try {
            Role role = new Role();
            BeanUtils.copyProperties(roleDTO, role);
//            role.setMenuList(roleDTO.getMenuList().toString());
            role.setUpdateDate(new Date());
            update = roleMapper.updateById(role);

        } catch (Exception e) {
            throw new AppException("修改角色失败！");
        }
        if (update != 0){
            return R.ok("success");
        }else return R.error("Failure");
    }

    @Override
    @OperationLog(value = EnumTypeValue.USER_PERMISSIONS, description = EnumOperationLog.ROLE_DELETION)
    public R delUserList(Integer id) {
        try {
            if(id != 0 && id != null){
                QueryWrapper<UserAndRole> wrapper = new QueryWrapper<>();
                wrapper.eq("role_id",id);
                userAndRoleMapper.delete(wrapper);

                int i = roleMapper.deleteById(id);
                if (i != 0){
                    return R.ok("success");
                }else return R.error("Failure");

            }
        } catch (Exception e) {
            throw new AppException("删除角色失败！");
        }

        return null;
    }

}
